#!/bin/bash

source ~/.bashrc
conda activate coin2_motion_env

COIN_ROOT="$(git rev-parse --show-toplevel)"
export RESULT_PATH=${REMOTE_HOME}/shared/sim_result
COIN_BINARY_ROOT=${COIN_ROOT}/../coin_binary
JSON_PATH=${COIN_ROOT}/cc/appcoin2/research/example/vanilla_call.json
mkdir -p ${RESULT_PATH}

arg=$1
if [[ "$arg" == "true" ]]; then
  is_pure_dh=true
else
  is_pure_dh=false
fi


json=$(cat ${JSON_PATH})

export max_maturity=0
for option in $(echo "$json" | jq -c '.option_configs[]'); do
  time_to_maturity=$(echo "$option" | jq -r '.time_to_maturity')
  if (( $(echo "$time_to_maturity > $max_maturity" | bc -l) )); then
    max_maturity=$time_to_maturity
  fi
done

export project_name=$(echo $json | jq -r '.project_name')
export symbol=$(echo $json | jq -r '.symbol')
export mandate_price_rate=$(echo $json | jq -r '.mandate_price_rate')
export TEXT_RESULT_PATH=${RESULT_PATH}/${project_name}_${symbol}.txt
export is_pure_dh=$is_pure_dh

${COIN_BINARY_ROOT}/coin2-bazel-bin-3.10/cc/appcoin2/research/option_calculator \
  --config=$JSON_PATH --is_pure_dh=$is_pure_dh 


PYTHON_SCRIPT='
from PIL import Image, ImageDraw, ImageFont;
import os;
import datetime
from xunkemgmt_client.tool.slack_noti import send_to_slack
with open(os.getenv("TEXT_RESULT_PATH"), "r") as file:
  text = file.read();
draw = ImageDraw.Draw(Image.new("RGB", (1, 1)));
x0, y0, width, height = draw.textbbox((0, 0), text);
left_margin = 100;
right_margin = 100;
dpi = 1000;
image = Image.new("RGB", ((width - x0 + left_margin + right_margin), (height - y0)), color = "white");
draw = ImageDraw.Draw(image);
tabsize = 4;
text = text.replace("\t", " " * tabsize);

font_size = 10;
font_path = os.path.join(os.getenv("COIN_DEPLOY_REPO"), "support_day1mm/mm_report/Montserrat-Regular.ttf");
font = ImageFont.truetype(font_path, font_size);

draw.text((-x0 + left_margin, -y0), text, fill="black", font=font);
final_img_name = os.getenv("RESULT_PATH")+"/"+os.getenv("project_name")+"_"+os.getenv("symbol")+ "_"+ os.getenv("max_maturity") + "Y_" + datetime.datetime.utcnow().strftime("%Y%m%d_%H%M%S");
if isinstance(os.getenv("is_pure_dh"), bool) and os.getenv("is_pure_dh") or os.getenv("is_pure_dh") == "true":
  final_img_name += "_pure_dh_mpr_" + os.getenv("mandate_price_rate");
image.save(final_img_name+ ".png", dpi=(dpi, dpi))
send_to_slack("https://files.ap.ngrok.io" + final_img_name + ".png", "@" + os.getenv("USER"), "msg")
'

./pyrunner -c "${PYTHON_SCRIPT}"
